import Vue from "vue";
import Reply from './Reply-box'

const ReplyBoxContructor = Vue.extend(Reply);
let instance = null;

/**
 * 默认值
 */
const defaults = {
  content: '',
  placeholder: '回复支持 Markdown 语法',
  callback: function() {}
}

/**
 * 默认回调函数
 */
const defaultCallback = (instance, resolve, reject) => {
  return (content) => {
    instance.hide()
    return resolve(content)
  }
}

/**
 * 获取实例
 */
let getInstance = () => {
  if (!instance) {
    instance = new ReplyBoxContructor({
      el: document.createElement('div')
    })
  }
  resetInstance()
  return instance
}

/**
 * 初始化实例
 */
let resetInstance = () => {
  if (instance) {
    instance.content = defaults.content
    instance.placeholder = defaults.placeholder
    instance.callback = defaults.callback
    instance.hide()
  }
}

let replyBox = (options = {})=> {
  let instance = getInstance()

  instance.content = options.content || defaults.content
  instance.placeholder = options.placeholder || defaults.placeholder
  
  Vue.nextTick(() => {
    document.body.appendChild(instance.$el)
  })

  return new Promise((resolve, reject) => {
    instance.callback = defaultCallback(instance, resolve, reject)
    instance.show()
  })
}

export default replyBox